import { useState, useRef } from "react";

const useCountDown = (initialCount: number) => {
  const [count, setCount] = useState(0);
  const refStop = useRef<Function>();

  const stop = () => {
    if (refStop.current) {
      refStop.current();
      refStop.current = undefined;
    }

    setCount(0);
  };

  const start = () => {
    stop();

    let temp = initialCount;
    setCount(temp);

    const id = window.setInterval(() => {
      temp -= 1;
      if (temp <= 0) {
        stop();
      }
      setCount(temp);
    }, 1000);

    refStop.current = () => {
      window.clearInterval(id);
    };
  };

  return { count, start, stop };
};

export default useCountDown;
